<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Input &amp; Output in Visual Basic</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Input &amp; Visual Basic, learn Visual Basic, programming, language">
<meta name="description" content="This part of the Visual Basic tutorial covers input &amp; output in Visual Basic.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Input &amp; Output</h1>

<p>
This chapter is dedicated to Input &amp; Output in Visual Basic. 
The Input &amp; Output in Visual Basic is based on streams.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
Streams are objects to work with Input/Output. A stream is an abstraction
of a sequence of bytes, such as a file, an input/output device,
an inter-process communication pipe, or a TCP/IP socket. In Visual Basic,
we have a <code>Stream</code> class, that is an abstract class
for all streams. There are additional classes that derive from the Stream
class and make the programming a lot easier.
</p>


<h2>MemoryStream</h2>

<p>
A <code>MemoryStream</code> is a stream which works with 
data in a computer memory. 
</p>

<pre class="code">
Option Strict On


Imports System.IO

Module Example

   Sub Main()

      Dim ms As Stream = New MemoryStream(6)

      ms.WriteByte(9)
      ms.WriteByte(11)
      ms.WriteByte(6)
      ms.WriteByte(8)
      ms.WriteByte(3)
      ms.WriteByte(7)

      ms.Position = 0

      Dim rs As Integer
      rs = ms.ReadByte()

      Do While rs &lt;&gt; -1
        Console.WriteLine(rs)
        rs = ms.ReadByte()
      Loop

      ms.Close()

   End Sub 

End Module
</pre>

<p>
We write six numbers to a memory with a <code>MemoryStream</code>.
Then we read those numbers and print them to the console. 
</p>

<pre class="explanation">
Dim ms As Stream = New MemoryStream(6)
</pre>

<p>
The line creates and initializes a <code>MemoryStream</code> 
object with a capacity of six bytes. 
</p>

<pre class="explanation">
ms.Position = 0
</pre>

<p>
We set the position of the cursor in the stream to 
the beginning using the <code>Position</code> property.
</p>

<pre class="explanation">
ms.WriteByte(9)
ms.WriteByte(11)
ms.WriteByte(6)
...
</pre>

<p>
The <code>WriteByte()</code> method writes a byte to the current 
stream at the current position.
</p>

<pre class="explanation">
Do While rs &lt;&gt; -1
  Console.WriteLine(rs)
  rs = ms.ReadByte()
Loop
</pre>

<p>
Here we read all bytes from the stream and print them to the console. 
</p>

<pre class="explanation">
ms.Close()
</pre>

<p>
Finally, we close the stream.
</p>

<pre>
$ ./memory.exe 
9
11
6
8
3
7
</pre>

<p>
Output of the example. 
</p>


<h2>StreamReader &amp; StreamWriter</h2>

<p>
<code>StreamReader</code> reads characters from a byte stream. 
It defaults to UTF-8 encoding. <code>StreamWriter</code> writes
characters to a stream in a particular encoding. 
</p>


<pre class="code">
Option Strict On

Imports System.IO

Module Example

   Sub Main()

       Dim file As String
       file = "languages"
         
       Try
           Dim stream As StreamReader
           stream = New StreamReader(file)
           Console.WriteLine(stream.ReadToEnd())
       Catch e As IOException
           Console.WriteLine("Cannot read file.")
       End Try

   End Sub 

End Module
</pre>

<p>
We have a file called languages. We read characters from that
file and print them to the console. 
</p>

<pre class="explanation">
Dim stream As StreamReader
stream = New StreamReader(file)
</pre>

<p>
The <code>StreamReader</code> takes a file name as a
parameter.
</p>

<pre class="explanation">
Console.WriteLine(stream.ReadToEnd())
</pre>

<p>
The <code>ReadToEnd()</code> method reads all characters
to the end of the stream. 
</p>


<pre>
$ cat languages 
Python
Visual Basic
PERL
Java
C
C#
$ ./readfile.exe 
Python
Visual Basic
PERL
Java
C
C#
</pre>

<p>
We have a languages file in the current directory. We print all lines
of the file to the console. 
</p>

<hr class="btm">

<p>
In the next example, we will be counting lines. 
</p>

<pre class="code">
Option Strict On

Imports System.IO

Module Example

   Sub Main()

       Dim file As String
       Dim count As Integer

       file = "languages"
         
       Try
           Dim stream As StreamReader
           stream = New StreamReader(file)
              
           While Not (stream.ReadLine() Is Nothing)
               count += 1
           End While

       Catch e As IOException
           Console.WriteLine("Cannot read file.")
       End Try

       Console.WriteLine("There are {0} lines", count)

   End Sub 

End Module
</pre>

<p>
Counting lines in a file. 
</p>

<pre class="explanation">
While Not (stream.ReadLine() Is Nothing)
    count += 1
End While
</pre>

<p>
In the While loop, we read a line from the stream with
the <code>ReadLine()</code> method. It returns a
line from the stream or Nothing if the end of the input 
stream is reached.
</p>

<hr class="btm">

<p>
An example with <code>StreamWriter</code> follows.
</p>

<pre class="code">
Option Strict On

Imports System.IO

Module Example

   Sub Main()

      Dim mstream As New MemoryStream()
      Dim swriter As New StreamWriter(mstream)

      swriter.Write("ZetCode, tutorials for programmers.")
      swriter.Flush()
      
      Dim sreader As New StreamReader(mstream)
      Console.WriteLine(sreader.ReadToEnd())
      sreader.Close()

   End Sub 

End Module
</pre>

<p>
In the preceding example, we write characters to the memory.
</p>

<pre class="explanation">
Dim mstream As New MemoryStream()
</pre>

<p>
A <code>MemoryStream</code> is created.
</p>

<pre class="explanation">
Dim swriter As New StreamWriter(mstream)
</pre>

<p>
A <code>StreamWriter</code> class takes a
memory stream as a parameter. This way, we are going
to write to memory stream.
</p>

<pre class="explanation">
swriter.Write("ZetCode, tutorials for programmers.")
swriter.Flush()
</pre>

<p>
We write some text to the writer. The <code>Flush()</code>
clears all buffers for the current writer and causes any buffered data
to be written to the underlying stream.
</p>

<pre class="explanation">
Dim sreader As New StreamReader(mstream)
Console.WriteLine(sreader.ReadToEnd())
</pre>

<p>
Now we create an instance of the stream reader and
read everything we have written back.
</p>


<h2>FileStream</h2>

<p>
A <code>FileStream</code> class uses a stream on a file on
the filesystem. This class can be used to read from files, write to files, open
them and close them. 
</p>

<pre class="code">
Option Strict On

Imports System.IO
Imports System.Text

Module Example

   Sub Main()
        Dim fstream As New FileStream("author", FileMode.Append)
        Dim bytes As Byte() = New UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский")

        fstream.Write(bytes, 0, bytes.Length)
        fstream.Close()
   End Sub 

End Module
</pre>

<p>
We write some text in Russian azbuka to the file in the current working directory.
</p>


<pre class="explanation">
Dim fstream As New FileStream("author", FileMode.Append)
</pre>

<p>
A <code>FileStream</code> object is created. The second
parameter is a mode, in which the file is opened. 
The append mode opens the file if it exists and seeks to the end 
of the file, or creates a new file.
</p>

<pre class="explanation">
Dim bytes As Byte() = New UTF8Encoding().GetBytes("Фёдор Михайлович Достоевский")
</pre>

<p>
We create an array of bytes from text in russian azbuka. 
</p>

<pre class="explanation">
fstream.Write(bytes, 0, bytes.Length)
</pre>

<p>
We write the bytes to the file stream. 
</p>


<h2>XmlTextReader</h2>

<p>
We can use streams to read xml data. The <code>XmlTextReader</code> is the class to read xml files in Visual Basic.
The class is forward-only and read-only. 
</p>

<p>
We have the following xml test file. 
</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;languages&gt;
    &lt;language&gt;Python&lt;/language&gt;
    &lt;language&gt;Ruby&lt;/language&gt;   
    &lt;language&gt;Javascript&lt;/language&gt;
    &lt;language&gt;C#&lt;/language&gt;
&lt;/languages&gt;
</pre>


<pre class="code">
Option Strict On

Imports System.IO
Imports System.Xml

Module Example

    Sub Main()

        Dim file As String
        file = "languages.xml"
      
        Try
            Dim xreader As New XmlTextReader(file)

            xreader.MoveToContent()

            Do While xreader.Read()
                Select Case xreader.NodeType
                    Case XmlNodeType.Element
                        Console.Write(xreader.Name &amp; ": ")
                    Case XmlNodeType.Text
                        Console.WriteLine(xreader.Value)
                End Select
            Loop
 
            xreader.Close()
 
        Catch e As IOException
            Console.WriteLine("Cannot read file.")
        Catch e As XmlException
            Console.WriteLine("XML parse error")
        End Try

     End Sub 

End Module
</pre>

<p>
This Visual Basic program reads data from the previously
specified xml file and prints it to the terminal. 
</p>

<pre class="explanation">
Dim xreader As New XmlTextReader(file)
</pre>

<p>
An <code>XmlTextReader</code> object is created.
It takes the file name as a parameter. 
</p>

<pre class="explanation">
xreader.MoveToContent()
</pre>

<p>
The <code>MoveToContent()</code> method moves to the
actual content of the xml file. 
</p>

<pre class="explanation">
Do While xreader.Read()
</pre>

<p>
This line reads the next node from the stream. 
</p>

<pre class="explanation">
Case XmlNodeType.Element
    Console.Write(xreader.Name &amp; ": ")
Case XmlNodeType.Text
    Console.WriteLine(xreader.Value)
</pre>

<p>
Here we print the element name and element text.
</p>

<pre class="explanation">
Catch e As XmlException
    Console.WriteLine("XML parse error")
</pre>

<p>
We check for xml parse error.
</p>

<pre>
$ ./readxml.exe 
language: Python
language: Ruby
language: Javascript
language: C#
</pre>

<p>
Output of example.
</p>

<h2>Files and directories</h2>

<p>
The .NET framework provides other classes that we can 
use to work with files and directories. 
</p>

<p>
A <code>File</code> class is a higher level class that
has shared methods for file creation, deletion, copying, moving and opening. 
These methods make the job easier. 
</p>

<pre class="code">
Option Strict On

Imports System.IO

Module Example

    Sub Main()
       Try        
            Dim sw As StreamWriter

            sw = File.CreateText("cars")

            sw.WriteLine("Toyota")
            sw.WriteLine("Skoda")
            sw.WriteLine("BMW")
            sw.WriteLine("Volkswagen")
            sw.WriteLine("Volvo")

            sw.Close()
       Catch e As IOException
           Console.WriteLine("IO error")
       End Try

    End Sub

End Module
</pre>

<p>
In the example, we create a cars file and write
some car names into it. 
</p>

<pre class="explanation">
sw = File.CreateText("cars")
</pre>

<p>
The <code>CreateText()</code> method creates or 
opens a file for writing UTF-8 encoded text. It returns
a <code>StreamWriter</code> object. 
</p>

<pre class="explanation">
sw.WriteLine("Toyota")
sw.WriteLine("Skoda")
...
</pre>

<p>
We write two lines to the stream. 
</p>

<hr class="btm">

<pre class="code">
Option Strict On

Imports System.IO

Module Example

    Sub Main()
                
        If File.Exists("cars")
            Console.WriteLine(File.GetCreationTime("cars"))
            Console.WriteLine(File.GetLastWriteTime("cars"))
            Console.WriteLine(File.GetLastAccessTime("cars"))
        End If

        File.Copy("cars", "newcars")

    End Sub

End Module
</pre>

<p>
In the second example, we show other five shared methods of the
File class. 
</p>

<pre class="explanation">
If File.Exists("cars")
</pre>

<p>
The <code>Exists()</code> method determines whether 
the specified file exists. 
</p>

<pre class="explanation">
Console.WriteLine(File.GetCreationTime("cars"))
Console.WriteLine(File.GetLastWriteTime("cars"))
Console.WriteLine(File.GetLastAccessTime("cars"))
</pre>

<p>
We get creation time, last write time and last access
time of the specified file. 
</p>

<pre class="explanation">
File.Copy("cars", "newcars")
</pre>

<p>
The <code>Copy()</code> method copies the file. 
</p>

<hr class="btm">

<p>
The <code>My.Computer.FileSystem</code> is and object, which 
provides properties and methods for working with drives, files, and directories.
</p>

<pre class="code">
Option Strict On

Imports System.IO

Module Example

    Sub Main()

        Try
            My.Computer.FileSystem.CreateDirectory("temp")
            My.Computer.FileSystem.CreateDirectory("newdir")
            My.Computer.FileSystem.MoveDirectory("temp", "temporary")
        Catch e As IOException
            Console.WriteLine("Cannot create directories")
            Console.WriteLine(e.Message)
        End Try

    End Sub

End Module
</pre>

<p>
We will use two methods from the above mentioned object. 
</p>

<pre class="explanation">
My.Computer.FileSystem.CreateDirectory("temp")
</pre>

<p>
The <code>CreateDirectory()</code> method creates a new
directory.
</p>

<pre class="explanation">
My.Computer.FileSystem.MoveDirectory("temp", "temporary")
</pre>

<p>
The <code>MoveDirectory()</code> method gives a specified
directory a new name.
</p>

<hr class="btm">

<p>
The <code>DirectoryInfo</code> and <code>Directory</code>
have methods for creating, moving, and enumerating through directories and subdirectories.
</p>

<pre class="code">
Option Strict On

Imports System.IO

Module Example

    Dim subDir As IO.DirectoryInfo
    Dim dir As New IO.DirectoryInfo("../io")

    Dim fileName As String

    Dim files As String() = Directory.GetFiles("../io")
    Dim dirs As DirectoryInfo() = dir.GetDirectories()

    Sub Main()
                
        For Each subDir In dirs
            Console.WriteLine(subDir.Name)
        Next
                
        For Each fileName In files
            Console.WriteLine(fileName)
        Next 

    End Sub

End Module
</pre>

<p>
We use the <code>DirectoryInfo</code> class to traverse a
specific directory and print its contents. 
</p>

<pre class="explanation">
Dim dir As New IO.DirectoryInfo("../io")
</pre>

<p>
We will show the contents of this directory (io).
</p>

<pre class="explanation">
Dim files As String() = Directory.GetFiles("../io")
</pre>

<p>
We get all files of the io directory using the shared
<code>GetFiles()</code> method.
</p>

<pre class="explanation">
Dim dirs As DirectoryInfo() = dir.GetDirectories()
</pre>

<p>
We get all directories. 
</p>


<pre class="explanation">
For Each subDir In dirs
    Console.WriteLine(subDir.Name)
Next
</pre>

<p>
Here we loop through directories and print their names
to the console. 
</p>

<pre class="explanation">
For Each fileName In files
    Console.WriteLine(fileName)
Next 
</pre>

<p>
Here we loop through the array of files and print
their names to the console. 
</p>

<pre>
$ ./showcontents.exe 
newdir
temp
temporary
../io/append.exe
../io/append.vb
../io/append.vb~
../io/author
../io/cars
...
</pre>

<p>
Output of the example. 
</p>


<p>
In this chapter, we have covered Input/Output operations in Visual Basic. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 21, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

